# pip install 'pymongo[srv]'
# pip install dnspython
import os
import sys
import  pymongo
import pandas as pd

import dxw
import com

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
global client
try:
    client = pymongo.MongoClient(
        "mongodb+srv://ltsjim:ltsjack123@cluster0.x6bey.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
    #print(client)
except:
    client = pymongo.MongoClient(
        "mongodb://ltsjim:ltsjack123@cluster0-shard-00-00.x6bey.mongodb.net:27017,cluster0-shard-00-01.x6bey.mongodb.net:27017,cluster0-shard-00-02.x6bey.mongodb.net:27017/admin?ssl=true&replicaSet=atlas-v4n9jm-shard-0&authSource=admin&retryWrites=true&w=majority")
today_time=com.time_saveandget()

def test():
    a=dxw.BK_analyse().zhangfu_main(10)
    mydb=client['web_data']
    mycol=mydb['text1']
    print("成功获得数据库",client.list_database_names())
    # 将DataFrame存入到mongodb中
    df = a.to_dict(orient='records')   # 固定写法
    #print(df)
    mycol.insert_many(df)
def mongo_insert(df,name):
    mydb = client['web_data']
    mycol = mydb['%s'%name]
    df = df.to_dict(orient='records')   # 固定写法
    mycol.insert_many(df)
    print("成功保存到mongodb altas/web_data/{}_{}上".format(name,today_time))
def read_df(name):
    mydb = client['web_data']
    mycol = mydb['%s' % name]
    df = pd.DataFrame(list(mycol.find({})))
    """
    <class 'pandas.core.frame.DataFrame'>
RangeIndex: 160 entries, 0 to 159
Data columns (total 15 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   _id                    160 non-null    object 
 1   所属概念                   160 non-null    object 
 2   code                   160 non-null    object 
 3   最新dde大单净额L1            160 non-null    object 
 4   市盈率(pe)[20211008]      160 non-null    float64
 5   最新价                    160 non-null    object 
 6   最新涨跌幅                  160 non-null    object 
 7   market_code            160 non-null    object 
 8   股票代码                   160 non-null    object 
 9   个股热度[20211010]         160 non-null    float64
 10  总股本[20211008]          160 non-null    int64  
 11  a股市值(不含限售股)[20211008]  160 non-null    float64
 12  所属同花顺行业                160 non-null    object 
 13  股票简称                   160 non-null    object 
 14  所属概念数量                 160 non-null    int64 
    """
    df1=df["所属概念"]
    for i in df["所属概念"]:
        print(i)

if __name__ == '__main__':
    test()
    # read_df("人气概念板块排名及行业")
    from stock import wencaicopy
    name="20211119人气及行业板块"
    df = wencaicopy.searchMain(name, 1)
    print(df)
    # mongo_insert(df,name)
